﻿using System;

namespace NModbus.Utility
{
    /// <summary>
    /// 数据类型转换工具（Integer、Float、Double互换ushort）
    /// </summary>
    public static class DataTypeConvertUtility
    {
        /// <summary>
        /// 将对象转换为ushort数组
        /// </summary>
        /// <param name="obj">数据对象</param>
        /// <param name="isBigEndian">是否为大端序，默认大端序</param>
        /// <returns>ushort数组</returns>
        /// <exception cref="Exception">不兼容数据类型转换异常</exception>
        public static ushort[] ConvertObjToUshort(object obj, bool isBigEndian = true)
        {
            ushort[] registers = new ushort[2];
            string typeName = obj.GetType().Name;
            byte[] bytes;
            switch (typeName)
            {
                case "Int32":
                    bytes = BitConverter.GetBytes(int.Parse(obj.ToString().Trim()));
                    break;
                case "Single":
                    bytes = BitConverter.GetBytes(float.Parse(obj.ToString().Trim()));
                    break;
                case "Double":
                    bytes = BitConverter.GetBytes(double.Parse(obj.ToString().Trim()));
                    registers = new ushort[4];
                    break;
                default:
                    throw new Exception("不受支持类型转换错误！");
            }
            if (isBigEndian)
            {
                // 大端序：高位在前（字节0-1 -> 寄存器0；字节2-3 -> 寄存器1）
                for  (int i = 0; i < bytes.Length / 2; i++)
                {
                    registers[i] = (ushort)((bytes[i * 2] << 8) | bytes[i * 2 + 1]);
                }
            }
            else
            {
                // 小端序：低位在前（字节1-0 -> 寄存器0；字节3-2 -> 寄存器1）
                for (int i = 0; i < bytes.Length / 2; i++)
                {
                    registers[i] = (ushort)((bytes[i * 2 + 1] << 8) | bytes[i * 2]);
                }
            }
            return registers;
        }
    }
}
